/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.nantai.jiafang.nantaijiafang.deviceManager.devicemanager;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.zxing.Result;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.Device;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.KeepTask;
import com.nantai.jiafang.nantaijiafang.deviceManager.camera.CameraManager;
import com.nantai.jiafang.nantaijiafang.deviceManager.Constans;
import com.nantai.jiafang.nantaijiafang.deviceManager.decode.DecodeThread;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.Error;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.HttpClient;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.ResponseHandler;
import com.nantai.jiafang.nantaijiafang.deviceManager.utils.BeepManager;
import com.nantai.jiafang.nantaijiafang.deviceManager.utils.CaptureActivityHandler;
import com.nantai.jiafang.nantaijiafang.deviceManager.utils.InactivityTimer;
import com.nantai.jiafang.nantaijiafang.deviceManager.utils.MessagePop;

import java.io.IOException;
import java.lang.reflect.Field;

import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * This activity opens the camera and does the actual scanning on a background
 * thread. It draws a viewfinder to help the user place the barcode correctly,
 * shows feedback as the image processing is happening, and then overlays the
 * results when a scan is successful.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
public final class CaptureActivity extends BaseActivity implements SurfaceHolder.Callback ,View.OnClickListener{

    private static final String TAG = CaptureActivity.class.getSimpleName();
    //@Bind(R.id.tv_toolbar_title)
    TextView mTvToolbarTitle;
    //@Bind(R.id.toolbar)
    Toolbar mToolbar;
    //@Bind(R.id.capture_mask_top)
    ImageView mCaptureMaskTop;
    //@Bind(R.id.capture_scan_line)
    ImageView mCaptureScanLine;
    //@Bind(R.id.capture_crop_view)
    RelativeLayout mCaptureCropView;
    //@Bind(R.id.capture_mask_bottom)
    ImageView mCaptureMaskBottom;
    //@Bind(R.id.capture_mask_left)
    ImageView mCaptureMaskLeft;
    //@Bind(R.id.capture_mask_right)
    ImageView mCaptureMaskRight;
    //@Bind(R.id.capture_container)
    RelativeLayout mCaptureContainer;
    //@Bind(R.id.toolbar_menu)
    TextView mToolbarMenu;

    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;

    private SurfaceView scanPreview = null;
    private RelativeLayout scanContainer;
    private RelativeLayout scanCropView;
    private ImageView scanLine;

    private Rect mCropRect = null;

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    private boolean isHasSurface = false;
    private int operate_type = 0;
    private MaterialDialog showDialog = null;
    private MaterialDialog repairDialog = null;
    private String mQrcode = null;
    private String taskid = null;
    private String placeid = null;
    private int selectIndex =0;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_capture);
        /*=============================*/
        mTvToolbarTitle=(TextView)findViewById(R.id.tv_toolbar_title);
        mToolbar=(Toolbar)findViewById(R.id.toolbar);
        mCaptureMaskTop=(ImageView)findViewById(R.id.capture_mask_top);
        mCaptureScanLine=(ImageView)findViewById(R.id.capture_scan_line);
        mCaptureCropView=(RelativeLayout)findViewById(R.id.capture_crop_view);
        mCaptureMaskBottom=(ImageView)findViewById(R.id.capture_mask_bottom);
        mCaptureMaskLeft=(ImageView)findViewById(R.id.capture_mask_left);
        mCaptureMaskRight=(ImageView)findViewById(R.id.capture_mask_right);
        mCaptureContainer=(RelativeLayout)findViewById(R.id.capture_container);
        mToolbarMenu=(TextView)findViewById(R.id.toolbar_menu);
        mToolbarMenu.setOnClickListener(this);
        /*===============================*/
       // ButterKnife.bind(this);

        mTvToolbarTitle.setText("扫描条码");
        mToolbar.setNavigationIcon(R.drawable.md_nav_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mToolbarMenu.setText(" 输入条码 ");


        scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
        scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
        scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
        scanLine = (ImageView) findViewById(R.id.capture_scan_line);

        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);

        TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
                0.9f);
        animation.setDuration(4500);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.RESTART);
        scanLine.startAnimation(animation);

        operate_type = Integer.valueOf(getIntent().getStringExtra("operate_type"));
        mQrcode = getIntent().getStringExtra("qrcode");
        taskid = getIntent().getStringExtra("taskid");
        placeid = getIntent().getStringExtra("placeid");
        String select_str =getIntent().getStringExtra("selectIndex");
        if(select_str!=null)
        {
            selectIndex =Integer.parseInt(select_str);
        }

        showDialog = new MaterialDialog.Builder(CaptureActivity.this)
                .content("正在请求数据")
                .progress(true, 0, false)
                .cancelable(false).build();

    }

    @Override
    protected void onResume() {
        super.onResume();

        // CameraManager must be initialized here, not in onCreate(). This is
        // necessary because we don't
        // want to open the camera driver and measure the screen size if we're
        // going to show the help on
        // first launch. That led to bugs where the scanning rectangle was the
        // wrong size and partially
        // off screen.
        cameraManager = new CameraManager(getApplication());

        handler = null;

        if (isHasSurface) {
            // The activity was paused but not stopped, so the surface still
            // exists. Therefore
            // surfaceCreated() won't be called, so init the camera here.
            initCamera(scanPreview.getHolder());
        } else {
            // Install the callback and wait for surfaceCreated() to init the
            // camera.
            scanPreview.getHolder().addCallback(this);
        }

        inactivityTimer.onResume();
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        if (!isHasSurface) {
            scanPreview.getHolder().removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isHasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     *
     * @param rawResult The contents of the barcode.
     * @param bundle    The extras
     */
    public void handleDecode(Result rawResult, Bundle bundle) {
        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();
        requestQrcode(rawResult.getText());
    }

    @Override//(R.id.toolbar_menu)
    public void onClick(View view) {
        onPause();
        MaterialDialog dialog = new MaterialDialog.Builder(CaptureActivity.this)
                .title("")
                .negativeText("取消")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        resetCamera();
                    }
                } )
                .inputType(InputType.TYPE_CLASS_NUMBER)
                .input("输入条码", null, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(MaterialDialog dialog, CharSequence input) {
                        // Do something
                        if (input.toString() != null && input.toString() != "" && input.toString().length() == 12) {
                            requestQrcode(input.toString());
                        } else {
                            resetCamera();
                            MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "请输入正确的条码");
                        }
                    }
                }).cancelable(false).show();
    }

    private void requestQrcode(String qrcode) {
        //扫码结果
        switch (operate_type) {
            case Constans.ScanCode: {
                Intent intent = getIntent();
                intent.putExtra("qrcode", qrcode);
                CaptureActivity.this.setResult(20, intent);
                CaptureActivity.this.finish();
            }
            break;
            case Constans.KeepCode: {
                final String qr_code = qrcode;
                requestKeepDevice(qr_code);

            }
            break;
            case Constans.RepiarCode: {
                requestDeviceStatus(qrcode);
            }
            break;
            case Constans.CheckCode: {
                requestDeviceDetail(qrcode);
            }
            break;
            case Constans.TaskCode: {
                requestCheckDevice(qrcode);
            }
            break;
        }
    }

    private void resetCamera() {
        onPause();
        onResume();
    }

    private void requestCheckDevice(String qrcode) {
        if (qrcode.length() != 12) {
            MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "请扫描正确的条码");
            resetCamera();
            return;
        }
        final String codeStr=qrcode;
        String title = "对设备:"+qrcode+"进行盘点";
        MaterialDialog dialog = new MaterialDialog.Builder(CaptureActivity.this)
                .title(title).negativeText("取消").positiveText("盘点").onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showDialog.show();
                        HttpClient client = new HttpClient(CaptureActivity.this.getApplicationContext());
                        Call call = client.service().checkDevice(placeid, taskid,codeStr);
                        client.request(call, new ResponseHandler<ResponseBody>() {
                            @Override
                            public void onSuccess(ResponseBody device) {
                                showDialog.dismiss();
                                MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "盘点成功");
                                resetCamera();
                            }

                            @Override
                            public void onFailure(int code, Error e) {
                                showDialog.dismiss();
                                resetCamera();
                                if (code != 404) {
                                    MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), e.getMessage());
                                } else {
                                    MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "网络异常");
                                }

                            }
                        });
                    }
                }).onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        resetCamera();
                    }
                }).cancelable(false).show();




    }

    private void requestKeepDevice(String qrcode) {
        if (qrcode.length() != 12) {
            MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "请扫描正确的条码");
            resetCamera();
            return;
        }
        if (mQrcode!=null&&!mQrcode.equals(qrcode)) {
            MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "请扫描对应的条码");
            resetCamera();
            return;
        }

        showDialog.show();
        HttpClient client = new HttpClient(CaptureActivity.this.getApplicationContext());
        Call call = client.service().getKeepDeviceInfo(qrcode);
        client.request(call, new ResponseHandler<KeepTask>() {
            @Override
            public void onSuccess(KeepTask device) {
                showDialog.dismiss();
                Intent intent = getIntent();
                intent.putExtra("device",device);
                CaptureActivity.this.setResult(20, intent);
                CaptureActivity.this.finish();
            }

            @Override
            public void onFailure(int code, Error e) {
                showDialog.dismiss();
                resetCamera();
                if (code != 404) {
                    MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), e.getMessage());
                } else {
                    MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), e.getMessage());
                    MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "网络异常");
                }

            }
        });
    }

    private void requestDeviceDetail(String qrcode) {
        if (qrcode.length() != 12) {
            MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "请扫描正确的条码");
            resetCamera();
            return;
        }
        showDialog.show();
        HttpClient client = new HttpClient(CaptureActivity.this.getApplicationContext());
        Call call = client.service().inspectDevice(qrcode);
        client.request(call, new ResponseHandler<Device>() {
            @Override
            public void onSuccess(Device device) {
                //登陆成功，保存用户信息
                showDialog.dismiss();
                Intent intent = new Intent(CaptureActivity.this.getApplicationContext(), DeviceDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("deviceInfo", device);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void onFailure(int code, Error e) {
                showDialog.dismiss();
                resetCamera();
                if (code != 404) {
                    MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), e.getMessage());
                } else {
                    MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "网络异常");
                }

            }
        });
    }

    private void requestDeviceStatus(final String qrcode) {
        if (qrcode.length() != 12) {
            MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "请扫描正确的条码");
            resetCamera();
            return;
        }
        showDialog.show();
        HttpClient client = new HttpClient(CaptureActivity.this.getApplicationContext());
        Call call = client.service().getDeviceInfo(qrcode);
        client.request(call, new ResponseHandler<Device>() {
            @Override
            public void onSuccess(Device device) {
                //登陆成功，保存用户信息
                showDialog.dismiss();
                Intent intent = new Intent(CaptureActivity.this.getApplicationContext(), repairActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("deviceInfo", device);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void onFailure(int code, Error e) {
                showDialog.dismiss();
                resetCamera();
                if (code != 404) {
                    MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), e.getMessage());
                } else {
                    MessagePop.ToastMessage(CaptureActivity.this.getApplicationContext(), "网络异常");
                }

            }
        });

    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a
            // RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
            }

            initCrop();
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    private void displayFrameworkBugMessageAndExit() {
        // camera error
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage("相机打开出错，请稍后重试");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }

        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        builder.show();
    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
    }

    public Rect getCropRect() {
        return mCropRect;
    }

    /**
     * 初始化截取的矩形区域
     */
    private void initCrop() {
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;

        /** 获取布局中扫描框的位置信息 */
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);

        int cropLeft = location[0];
        int cropTop = location[1] - getStatusBarHeight();

        int cropWidth = scanCropView.getWidth();
        int cropHeight = scanCropView.getHeight();

        /** 获取布局容器的宽高 */
        int containerWidth = scanContainer.getWidth();
        int containerHeight = scanContainer.getHeight();

        /** 计算最终截取的矩形的左上角顶点x坐标 */
        int x = cropLeft * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的左上角顶点y坐标 */
        int y = cropTop * cameraHeight / containerHeight;

        /** 计算最终截取的矩形的宽度 */
        int width = cropWidth * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的高度 */
        int height = cropHeight * cameraHeight / containerHeight;

        /** 生成最终的截取的矩形 */
        mCropRect = new Rect(x, y, width + x, height + y);
    }

    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void onBackPressed() {
        return;
    }
}